package m.base.service;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.JsonObject;
import m.base.model.StoreInfo;
import m.base.model.UserInfo;
import m.common.model.MigrationModel;
import m.common.model.Model;
import m.common.model.config.ModelConfig;
import m.common.model.util.*;
import m.common.service.Service;
import m.system.cache.CacheUtil;
import m.system.db.TransactionManager;
import m.system.exception.MException;
import m.system.util.ClassUtil;
import m.system.util.DateUtil;
import m.system.util.GenerateID;
import manage.model.AdminGroup;
import manage.model.OrgGroupView;
import manage.model.StatusModel;
import manage.service.AdminGroupService;
import manage.util.DictionaryUtil;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class StoreInfoService extends Service {
    /**
     * 添加商户
     */
    public StoreInfo addStoreInfo(StoreInfo model) throws Exception {
        String oid=GenerateID.generatePrimaryKey();
        AdminGroup org=new AdminGroup();
        org.setNum(oid);
        org.setName(model.getName());
        org.setParent(model.getParent());
        org.setType(AdminGroup.Type_Org);
        org.setBusiness(AdminGroup.Business_Business);
        org.setDescription(model.getDescription());
        ModelCheckUtil.checkUniqueCombine(model, new String[]{"name", "parent.oid"},"商户名称已存在");
        getService(AdminGroupService.class).save(org);
        model.setOid(oid);
        model.setLevel(getService(LevelInfoService.class).getApplyLevel());
        model.setLevelEndDate(DateUtil.getAddMonth(new Date(),3));
        model.setAccountDay("15");
        ModelUpdateUtil.updateModel(model,"level.oid","levelEndDate","types","tel","address","accountDay");
        return ModelQueryList.getModel(StoreInfo.class,oid,"*");
    }

    /**
     * 获取商户用户数量
     */
    public int getStoreUserNum(String storeOid) throws SQLException, MException {
        List<JSONObject> ls=ModelQuery.init(UserInfo.class)
            .addCollectExp("num","count(#{oid})")
            .addCondition(QueryCondition.eq("createStoreOid",storeOid))
            .addCondition(QueryCondition.eq("status", StatusModel.Status_Enable))
            .queryCollect(new QueryPage(0,1));
        if(ls.isEmpty()) return 1;
        else return ls.get(0).getInteger("num");
    }

    /**
     * 设置级别
     */
    public void setLevel(String storeOid, String levelOid, Date levelEndDate) throws MException {
        ModelUpdate.init(StoreInfo.class)
            .set("level.oid",levelOid)
            .set("levelEndDate",levelEndDate)
            .execute(storeOid);
        CacheUtil.clear(StoreInfo.class);
        DictionaryUtil.clear(AdminGroup.class);
        CacheUtil.clear(AdminGroup.class);
        CacheUtil.clear(OrgGroupView.class);
    }

    /**
     * 删除商家所有数据
     */
    public void deleteAllData(String storeOid) throws Exception {
        TransactionManager tm=new TransactionManager();
        try {
            tm.begin();
            List<Class<? extends Model>> classList = ModelConfig.getTableList();
            for (Class<? extends Model> clazz : classList) {
                if (MigrationModel.class.isAssignableFrom(clazz)) {
                    List<String> ls = ((MigrationModel) ClassUtil.newInstance(clazz)).migrationOidList(storeOid);
                    if (ls.isEmpty()) continue;
                    List<Model> deleteList = new ArrayList<>();
                    for (String oid : ls) {
                        Model model = ClassUtil.newInstance(clazz);
                        model.setOid(oid);
                        deleteList.add(model);
                    }
                    ModelUpdateUtil.deleteModels(deleteList.toArray(new Model[0]));
                }
            }
            tm.commit();
        }catch (Exception e){
            tm.rollback();
            throw e;
        }
    }
}
